package com.leetcodehot.problems;

import java.util.ArrayDeque;
import java.util.Deque;

public class problems513 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 方法一：层序遍历返回第一个
     */
    /*public int findBottomLeftValue(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.push(root);
        int ans = -1;
        while (!deque.isEmpty()) {
            int n = deque.size();
            ans = deque.getFirst().val;
            while (n-- > 0) {
                TreeNode node = deque.pollFirst();
                if (node.left != null) {
                    deque.addLast(node.left);
                }
                if (node.right != null) {
                    deque.addLast(node.right);
                }
            }
        }
        return ans;
    }*/

    /**
     * 做法二：层序遍历 先右后左，的最后一个
     */
    public int findBottomLeftValue(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.push(root);
        int ans = -1;
        while (!deque.isEmpty()) {
            int n = deque.size();
            while (n-- > 0) {
                TreeNode node = deque.pollFirst();
                if (node.right != null) {
                    deque.addLast(node.right);
                }
                if (node.left != null) {
                    deque.addLast(node.left);
                }
                ans = node.val;
            }
        }
        return ans;
    }
}
